from ability.cloud import CloudInstance
from ability.serializer.serializers import ImageSerializer
from ability.models import TempInstance, Image
from rest_framework import serializers
import json

class TempInstancesSerializer(serializers.ModelSerializer):

    image = serializers.SerializerMethodField()
    instance = serializers.SerializerMethodField()

    class Meta:
        model = TempInstance
        fields = ['id', 'instanceId', 'create_time', 'image', 'instance', 'image_name', 'status']

    def get_image(self, obj):
        return ImageSerializer(obj.image).data

    def get_instance(self, obj):
        instance = CloudInstance()
        ins = instance.DescribeInstance(obj.instanceId)
        if ins is None:
            return None

    # {"Placement": {"Zone": "ap-beijing-2", "ProjectId": 0, "HostIds": null, "HostIps": null, "HostId": null}, "InstanceId": "ins-i4punzgl", "InstanceType": "S3.SMALL1", "CPU": 1, "Memory": 1, "RestrictState": "NORMAL", "InstanceName": "Ubuntu20-04-python", "InstanceChargeType": "POSTPAID_BY_HOUR", "SystemDisk": {"DiskType": "CLOUD_PREMIUM", "DiskId": "disk-i2pup5gn", "DiskSize": 50}, "DataDisks": [{"DiskSize": 100, "DiskType": "CLOUD_PREMIUM", "DiskId": "disk-qd4rcquh", "DeleteWithInstance": true, "SnapshotId": null, "Encrypt": null, "KmsKeyId": null}], "PrivateIpAddresses": ["172.21.0.21"], "PublicIpAddresses": null, "InternetAccessible": {"InternetChargeType": null, "InternetMaxBandwidthOut": 5, "PublicIpAssigned": null, "BandwidthPackageId": null}, "VirtualPrivateCloud": {"VpcId": "vpc-qer2esfe", "SubnetId": "subnet-3x5o0shn", "AsVpcGateway": false, "PrivateIpAddresses": null, "Ipv6AddressCount": null}, "ImageId": "img-3e4xohf9", "RenewFlag": null, "CreatedTime": "2021-02-03T10:02:15Z", "ExpiredTime": null, "OsName": "Ubuntu Server 20.04 LTS 64位", "SecurityGroupIds": ["sg-d5ow8457"], "LoginSettings": {"Password": null, "KeyIds": null, "KeepImageLogin": null}, "InstanceState": "STOPPED", "Tags": [], "StopChargingMode": "STOP_CHARGING", "Uuid": "499f897d-07ee-40ce-adef-7f850e78d390", "LatestOperation": "StopInstances", "LatestOperationState": "SUCCESS", "LatestOperationRequestId": "09921fdc-7132-4d27-a3e3-cc08c3516699", "DisasterRecoverGroupId": "", "IPv6Addresses": null, "CamRoleName": "", "HpcClusterId": "", "RdmaIpAddresses": null}
        return {
            "PrivateIpAddresses": ins.PrivateIpAddresses,
            "PublicIpAddresses": ins.PublicIpAddresses,
            "InstanceState": ins.InstanceState,
            "InstanceId": ins.InstanceId,
            "ImageId": ins.ImageId
        }